<?php
/*
Plugin Name: WebP
Plugin URI: https://www.beizigen.com/3670.html
Description: 上传图片时自动将图片转换为webp格式。
Version: 1.0.1
Author: 背字根
Author URI: https://www.beizigen.com/
Text Domain: webp
License: GPL v3 or later
License URI: http://www.gnu.org/licenses/gpl-3.0.txt
*/

if((extension_loaded('gd') && function_exists('imagewebp')) || (extension_loaded('imagick') && !empty(\Imagick::queryformats('webp')) ) ) {
    require_once('functions.php');
}

//添加菜单
add_action('admin_menu', function() {
	add_options_page('WebP转换', 'WebP转换', 'administrator', 'webp', 'webp_control');
});

//插件页面设置链接
add_filter('plugin_action_links', function($links, $file) {
	if($file == plugin_basename(__FILE__)) {
		array_unshift($links, '<a href="options-general.php?page=webp">设置</a>');
	}
	return $links;
}, 10, 2);

//卸载插件
register_uninstall_hook(__FILE__, 'webp_uninstall');

function webp_control() {
	if(isset($_POST['action']) && 'save' == $_POST['action']) {
		$quality = (int) $_POST['quality'];
		update_option('webp_quality', $quality);
		$maxwidth = (int) $_POST['maxwidth'];
		update_option('webp_width', $maxwidth);
		$maxheight = (int) $_POST['maxheight'];
		update_option('webp_height', $maxheight);
		echo '<div class="notice is-dismissible updated">设置保存成功！</div>';
	}

    if((!extension_loaded('gd') || !function_exists('imagewebp')) && (!extension_loaded('imagick') || empty(\Imagick::queryformats('webp')) ) ) {
        echo '<div class="notice is-dismissible error">本插件需要GD或Imagick扩展支持，并需要对WebP的支持，请联系您的主机服务商开启相关功能。</div>';
    }
?>

<style type="text/css">
    #wpwrap .notice {
        margin: 20px 20px 20px 0;
        padding: 1em;
    }
</style>

<form class="entry" method="post" action="<?php echo admin_url("options-general.php?page=webp"); ?>">
    <h2>WebP转换设置</h2>
    <p>自动将上传的JPG/PNG格式图片转换为WebP格式，不保留原图片。</p>
    <table class="form-table">
        <tr>
            <th scope="row"><label for="quality">图片质量</label></th>
            <td>
                <input id="quality" name="quality" class="small-text code" type="number" value="<?php echo get_option('webp_quality', 70); ?>"> %
            </td>
        </tr>
        <tr>
            <th scope="row"><label for="maxwidth">图片大小</label></th>
            <td>
                <p><input id="maxwidth" name="maxwidth" class="small-text code" type="number" value="<?php echo get_option('webp_width', 0); ?>"> 最大宽</p>
                <p><input id="maxheight" name="maxheight" class="small-text code" type="number" value="<?php echo get_option('webp_height', 0); ?>"> 最大高</p>
                <p class="description">图片按照设置宽高进行缩放，0为不限制。</p>
            </td>
        </tr>
    </table>
    <p class="submit">
        <input type="submit" class="button-primary" name="action" value="保存设置">
        <input type="hidden" name="action" value="save">
    </p>
</form>

<?php } ?>